package com.emergency.embackend.service.impl;

import cn.hutool.json.JSONUtil;
import com.emergency.embackend.entity.WikiType;
import com.emergency.embackend.exception.EmException;
import com.emergency.embackend.mapper.WikiTypeMapper;
import com.emergency.embackend.service.WikiTypeService;
import com.emergency.embackend.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class WikiTypeServiceImpl implements WikiTypeService {
    @Autowired
    private WikiTypeMapper wikiTypeMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<WikiType> getWikiType() {
        List<WikiType> typeList = new ArrayList<>();
        //先判断是否缓存命中
        String key = RedisConstants.WIKI_TYPE_KEY;
        Long size = stringRedisTemplate.opsForList().size(key);
        //缓存未命中
        if (size == 0) {
            typeList = wikiTypeMapper.getWikiType();
            if(typeList!=null) {
                for (WikiType wiki : typeList) {
                    String s = JSONUtil.toJsonStr(wiki);
                    stringRedisTemplate.opsForList().leftPush(key, s);
                }
                return typeList;
            }
            throw new EmException("500","数据查询为空");
        }

        for (int i = 0; i < size; i++) {
            String type = stringRedisTemplate.opsForList().leftPop(key);
            WikiType wikiType = JSONUtil.toBean(type, WikiType.class);
            typeList.add(wikiType);
        }
        return typeList;

    }

    @Override
    public void delete(Long typeId) {
        wikiTypeMapper.delete(typeId);
    }

    @Override
    public void add(WikiType wikiType) {
        wikiTypeMapper.add(wikiType);
    }
}
